package com.sxt.demo.djiapplication.view

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.TextView
import com.sxt.demo.djiapplication.databinding.LoadingLayoutBinding
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog

class LoadingView(val context: Context) {

    private val inflate: LoadingLayoutBinding =
        LoadingLayoutBinding.inflate(LayoutInflater.from(context))

    private val loadingArea by lazy { inflate.loadingArea }

    private lateinit var loadingDialog: MaterialDialog

    private var isLoading = false

    private var viewIndex = 0

    private val handler = Handler(Looper.myLooper()!!)

    /**
     * 显示加载对话框
     */
    fun showLoading(): LoadingView {
        loadingDialog = MaterialDialog.Builder(context)
            .customView(inflate.root, true)
            .limitIconToDefaultSize()
//            .title("进行中")
//            .content(R.string.content_wait_for_receive_data)
//            .progress(true, 0)
//            .progressIndeterminateStyle(false)
            .autoDismiss(false)
            .canceledOnTouchOutside(false)
            .show()
        isLoading = true
        return this
    }

    /**
     * 隐藏加载对话框
     */
    fun dismissLoading() {
        if (isLoading) {
            loadingArea.removeViews(0, viewIndex)
            viewIndex = 0
            loadingDialog.dismiss()
            isLoading = false
        }
    }

    fun dismissLoading(millis: Long) {
        handler.postDelayed({
            dismissLoading()
        }, millis)
    }

    /**
     * 设置加载提示文字
     */
    fun setLoadingText(text: String): LoadingView {
        loadingArea.removeViews(0, viewIndex)
        loadingArea.addView(newTextView(text), 0)
        viewIndex = 1
        return this
    }

    /**
     * 追加加载提示文字
     * 以一行计
     */
    fun appendLoadingText(text: String): LoadingView {
        loadingArea.addView(newTextView(text), viewIndex++)
        return this
    }

    /**
     * 根据给定的文本创建一个TextView
     */
    private fun newTextView(text: String): TextView {
        val textView = TextView(context)
        textView.text = text
        textView.gravity = Gravity.CENTER
        return textView
    }
}